package com.yami.shop.live.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.LiveInterfaceType;
import com.yami.shop.bean.enums.LiveProdStatusType;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.CharUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.live.common.constant.LiveConstant;
import com.yami.shop.live.common.model.LiveProdStore;
import com.yami.shop.live.common.model.LiveRoomProd;
import com.yami.shop.live.common.param.LiveUsableNumParam;
import com.yami.shop.live.common.service.LiveLogService;
import com.yami.shop.live.common.service.LiveProdStoreService;
import com.yami.shop.live.common.service.LiveRoomProdService;
import com.yami.shop.live.common.util.WxImageUtil;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author LGH
 * @date 2020-08-04 16:57:17
 */
@RestController
@AllArgsConstructor
@RequestMapping("/live/liveProdStore")
@Tag(name = "商家端直播间商品库接口")
public class LiveProdStoreController {

    private final LiveProdStoreService liveProdStoreService;
    private final LiveLogService liveLogService;
    private final ProductService productService;
    private final WxImageUtil wxImageUtil;
    private final LiveRoomProdService liveRoomProdService;
    private final ShopConfig shopConfig;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:page')")
    @Operation(summary =  "分页查找直播间商品库信息")
    public ServerResponseEntity<IPage<LiveProdStore>> getLiveProdStorePage(PageParam<LiveProdStore> page,@ParameterObject LiveProdStore liveProdStore) {
        liveProdStore.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<LiveProdStore> resPage = liveProdStoreService.getPage(page, liveProdStore);
        return ServerResponseEntity.success(resPage);
    }

    @GetMapping("/info/{liveProdStoreId}")
    @Operation(summary =  "通过id查询直播间商品库")
    @Parameter(name = "liveProdStoreId", description = "直播间商品库id", required = true)
    public ServerResponseEntity<LiveProdStore> getById(@PathVariable("liveProdStoreId") Long liveProdStoreId) {
        LiveProdStore liveProdStore = liveProdStoreService.getById(liveProdStoreId);
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), liveProdStore.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        if (Objects.nonNull(liveProdStore.getProdId())) {
            Product product = productService.getProductAndLang(liveProdStore.getProdId());
            if (product != null) {
                liveProdStore.setPic(product.getPic());
                liveProdStore.setProdName(product.getProdName());
                liveProdStore.setOriProdType(product.getProdType());
            }
        }
        return ServerResponseEntity.success(liveProdStore);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:save')")
    @Operation(summary =  "新增直播间商品")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid LiveProdStore liveProdStore) {
        if (CharUtil.length(liveProdStore.getName()) < LiveConstant.PROD_NAME_MIN_LENGTH
                || CharUtil.length(liveProdStore.getName()) > LiveConstant.PROD_NAME_MAX_LENGTH) {
            // 名称长度非法,最少3个汉字或者6个字符、最大14个汉字！
            throw new YamiShopBindException("yami.live.prod.name.check");
        }
        if (StrUtil.isBlank(liveProdStore.getUrl())) {
            // 请选择商品！
            throw new YamiShopBindException("yami.score.select.num");
        }
        // 判断直播商品封面图片大小是否不超过300px
        checkCoverPic(liveProdStore);
        liveProdStore.setShopId(SecurityUtils.getShopUser().getShopId());
        Date date = new Date();
        liveProdStore.setCreateTime(date);
        liveProdStore.setStatus(LiveProdStatusType.NO_EXAMINE.value());
        liveProdStore.setUpdateTime(date);
        liveProdStore.setVerifyTime(null);
        liveProdStore.setSuccessTime(null);
        liveProdStore.setGoodsId(null);
        return ServerResponseEntity.success(liveProdStoreService.save(liveProdStore));
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:update')")
    @Operation(summary =  "修改直播间商品")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid LiveProdStore liveProdStore) throws WxErrorException {
        if (CharUtil.length(liveProdStore.getName()) < LiveConstant.PROD_NAME_MIN_LENGTH || CharUtil.length(liveProdStore.getName()) > LiveConstant.PROD_NAME_MAX_LENGTH) {
            throw new YamiShopBindException("yami.live.prod.name.check");
        }
        if (!Objects.equals(liveProdStore.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        LiveProdStore dbProd = liveProdStoreService.getById(liveProdStore.getLiveProdStoreId());
        if(Objects.equals(dbProd.getStatus(), LiveProdStatusType.EXAMINING.value())){
            // 商品正在审核中，无法进行修改
            throw new YamiShopBindException("yami.live.prod.examine");
        }
        // 判断直播商品封面图片大小是否不超过300px
        checkCoverPic(liveProdStore);
        liveProdStore.setUpdateTime(new Date());
        liveProdStoreService.updateWxLiveProdById(liveProdStore);
        return ServerResponseEntity.success();
    }
    /**
     * 判断直播商品封面图片大小是否不超过300px
     * @param liveProdStore 直播商品信息
     */
    private void checkCoverPic(LiveProdStore liveProdStore) {
        String imgUrl = shopConfig.getDomain().getResourcesDomainName() + "/" + liveProdStore.getCoverPic();
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(new URL(imgUrl));
        } catch (IOException e) {
            e.printStackTrace();
            // 图片丢失，请重新上传图片
            throw new YamiShopBindException("yami.img.lose");
        }finally {

        }
        int width = bi.getWidth();
        int height = bi.getHeight();
        //直播商品封面长宽都不能超过300px
        if(width > 300 || height > 300){
            throw new YamiShopBindException("商品封面图片尺寸过大");
        }
    }

    @PutMapping("/submitVerify")
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:submitVerify')")
    @Operation(summary =  "提交审核")
    public ServerResponseEntity<Boolean> submitVerify(@RequestBody LiveProdStore liveProdStore) {
        liveProdStore = liveProdStoreService.getById(liveProdStore.getLiveProdStoreId());
        if (!Objects.equals(liveProdStore.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        if (Objects.equals(LiveProdStatusType.EXAMINING.value(), liveProdStore.getStatus())) {
            // 已提交审核
            throw new YamiShopBindException("yami.submitted.examine");
        }
        Product product = productService.getProductByProdId(liveProdStore.getProdId());
        if (Objects.isNull(product) || Objects.equals(product.getStatus(), StatusEnum.DELETE.value())) {
            // 当前直播商品关联的商品已被删除
            throw new YamiShopBindException("yami.live.prod.not.exist");
        }
        boolean b = liveProdStoreService.submitVerify(liveProdStore);
        return ServerResponseEntity.success(b);
    }

    @DeleteMapping("/{liveProdStoreId}")
    @PreAuthorize("@pms.hasPermission('live:liveProdStore:delete')")
    @Operation(summary =  "通过id删除直播间商品库")
    @Parameter(name = "liveProdStoreId", description = "直播间商品库id", required = true)
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long liveProdStoreId) throws WxErrorException {
        LiveProdStore prodStore = liveProdStoreService.getById(liveProdStoreId);
        if(!Objects.equals(prodStore.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            // 没有权限进行操作
            throw new YamiShopBindException("yami.no.auth");
        }
        liveProdStoreService.removeWxLiveProdById(liveProdStoreId, SecurityUtils.getShopUser().getShopId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/listAppleProds")
    @Operation(summary =  "获取微信入库的商品列表")
    @Parameters({
            @Parameter(name = "status", description = "商品状态 0：未审核。1：审核中，2：审核通过，3：审核驳回", required = true),
            @Parameter(name = "name", description = "商品名称", required = true),
            @Parameter(name = "id", description = "直播间id", required = true)
    })
    public ServerResponseEntity<IPage<LiveProdStore>> listAppleProds(PageParam<LiveProdStore> page, Integer status, String name, Integer id) {
        if (Objects.isNull(status)) {
            status = 2;
        }
        LiveProdStore liveProdStore = new LiveProdStore();
        liveProdStore.setStatus(status);
        liveProdStore.setName(name);
        liveProdStore.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<LiveProdStore> resPage = liveProdStoreService.getPage(page, liveProdStore);
        // 筛选掉已经选择的商品
        List<LiveRoomProd> prodList = liveRoomProdService.list(new LambdaQueryWrapper<LiveRoomProd>().eq(LiveRoomProd::getRoomId, id));
        List<LiveProdStore> liveProdStores = resPage.getRecords();
        // 筛选
        List<LiveProdStore> filterProdStores = liveProdStores.stream().filter(student -> prodList.stream().noneMatch(
                stuClass -> stuClass.getProdStoreId().equals(student.getLiveProdStoreId()))).collect(Collectors.toList());
        resPage.setRecords(filterProdStores);
        return ServerResponseEntity.success(resPage);
    }

    @GetMapping("/pageProdsByRoomId")
    @Operation(summary =  "根据直播间id获取直播间已经选择的商品")
    @Parameter(name = "id", description = "直播间id", required = true)
    public ServerResponseEntity<IPage<LiveProdStore>> pageProdsByRoomId(PageParam<LiveProdStore> page, Integer id) {
        IPage<LiveProdStore> resPage = liveProdStoreService.pageProdByRoomId(page, id);
        return ServerResponseEntity.success(resPage);
    }

    @GetMapping("/getAddProdNum")
    @Operation(summary =  "查询商家今日剩余可用添加直播商品、可删除商品库商品次数")
    public ServerResponseEntity<LiveUsableNumParam> getAddRoomNum() {
        LiveUsableNumParam liveNum = liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.ADD_PROD_AUDIT);
        LiveUsableNumParam deleteLiveNum = liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.DELETE_PROD);
        liveNum.setDeleteShopNum(deleteLiveNum.getShopNum());
        liveNum.setDeleteTotalNum(deleteLiveNum.getTotalNum());
        return ServerResponseEntity.success(liveNum);
    }

    @GetMapping("/getUpdateProdNum")
    @Operation(summary =  "查询商家今日剩余可用修改直播商品次数")
    public ServerResponseEntity<LiveUsableNumParam> getUpdateProdNum() {
        return ServerResponseEntity.success(liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.UPDATE_PROD));
    }

    @GetMapping("/getMediaId/{liveProdStoreId}")
    @Operation(summary =  "根据直播间商品库id获取信息")
    @Parameter(name = "liveProdStoreId", description = "直播间商品库id", required = true)
    public ServerResponseEntity<String> getMediaId(@PathVariable("liveProdStoreId") Long liveProdStoreId) {
        LiveProdStore liveProdStore = liveProdStoreService.getById(liveProdStoreId);
        return ServerResponseEntity.success(wxImageUtil.wxImageUpload(liveProdStore.getCoverPic()));
    }
}
